#!/usr/bin/env node

/**
 * 开发模式启动脚本
 * 自动安装插件并重启 Whistle
 */

const { exec } = require('child_process');
const path = require('path');

console.log('🚀 启动 Switcher3 开发模式...\n');

// 步骤列表
const steps = [
  {
    name: '安装插件到全局',
    command: 'npm install -g .',
    description: '将当前插件安装到全局 node_modules'
  },
  {
    name: '重启 Whistle',
    command: 'whistle restart',
    description: '重启 Whistle 以加载插件'
  }
];

// 执行步骤
async function runSteps() {
  for (let i = 0; i < steps.length; i++) {
    const step = steps[i];
    console.log(`📋 步骤 ${i + 1}/${steps.length}: ${step.name}`);
    console.log(`   ${step.description}`);
    console.log(`   执行: ${step.command}`);
    
    try {
      await executeCommand(step.command);
      console.log(`   ✅ 完成\n`);
    } catch (error) {
      console.error(`   ❌ 失败: ${error.message}\n`);
      process.exit(1);
    }
  }
  
  console.log('🎉 开发环境启动完成！\n');
  console.log('📝 接下来的步骤：');
  console.log('   1. 打开 Whistle 管理界面：http://local.whistlejs.com/');
  console.log('   2. 进入 Plugins 页面');
  console.log('   3. 找到 switcher3 插件并启用');
  console.log('   4. 点击 Option 按钮打开插件界面');
  console.log('');
  console.log('🔧 调试提示：');
  console.log('   - 后端日志：查看 Whistle 控制台输出');
  console.log('   - 前端日志：打开浏览器开发者工具');
  console.log('   - 重新加载：修改代码后运行 npm run dev');
}

// 执行命令
function executeCommand(command) {
  return new Promise((resolve, reject) => {
    const child = exec(command, { cwd: __dirname });
    
    child.stdout.on('data', (data) => {
      process.stdout.write(`   📤 ${data}`);
    });
    
    child.stderr.on('data', (data) => {
      process.stderr.write(`   📥 ${data}`);
    });
    
    child.on('close', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`命令执行失败，退出码: ${code}`));
      }
    });
    
    child.on('error', (error) => {
      reject(error);
    });
  });
}

// 处理中断信号
process.on('SIGINT', () => {
  console.log('\n\n⚠️ 用户中断操作');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n\n⚠️ 收到终止信号');
  process.exit(0);
});

// 启动
runSteps().catch((error) => {
  console.error('💥 启动失败:', error.message);
  process.exit(1);
});